package cn.stylefeng.guns.modular.order.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import cn.hutool.json.JSONObject;
import cn.stylefeng.guns.core.util.justApi;
import cn.stylefeng.guns.core.util.justCgrkApi;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.model.result.JHZYJDResult;
import cn.stylefeng.guns.modular.basic.service.*;
import cn.stylefeng.guns.modular.order.entity.OrderPutExcelItem;
import cn.stylefeng.guns.modular.replenishment.service.ReplenishmentOrderService;
import cn.stylefeng.guns.modular.tool.model.params.ToolOrderPutParam;
import cn.stylefeng.guns.modular.utils.JstDdcx;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jushuitan.api.ApiResponse;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Workbook;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicAddress;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicPutgoods;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicAddressParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicLineParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicPutgoodsParam;
import cn.stylefeng.guns.modular.order.entity.OutOrder;
import cn.stylefeng.guns.modular.order.model.params.OrderPutParam;
import cn.stylefeng.guns.modular.order.model.params.OrderTransportParam;
import cn.stylefeng.guns.modular.order.model.params.OutOrderDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OutOrderParam;
import cn.stylefeng.guns.modular.order.model.result.OrderTransportResult;
import cn.stylefeng.guns.modular.order.model.result.OutOrderDetailedResult;
import cn.stylefeng.guns.modular.order.model.result.OutOrderResult;
import cn.stylefeng.guns.modular.order.service.OrderPutService;
import cn.stylefeng.guns.modular.order.service.OrderTransportService;
import cn.stylefeng.guns.modular.order.service.OutOrderDetailedService;
import cn.stylefeng.guns.modular.order.service.OutOrderService;
import cn.stylefeng.guns.modular.storage.model.params.StorageOutParam;
import cn.stylefeng.guns.modular.storage.model.result.StorageOutResult;
import cn.stylefeng.guns.modular.storage.service.StorageOutDetailedService;
import cn.stylefeng.guns.modular.storage.service.StorageOutService;
import cn.stylefeng.guns.modular.transport.model.params.TransportReceiptParam;
import cn.stylefeng.guns.modular.transport.service.TransportReceiptService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.model.result.DictResult;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;

/**
 * 出库订单表控制器
 */
@Controller
@RequestMapping("/outOrder")
public class OutOrderController extends BaseController {

    private String PREFIX = "/order/outOrder";

    @Autowired
    private OutOrderService outOrderService;
    @Autowired
    private UserService userService;
    @Autowired
    private BasicCustomerService basicCustomerService;
    @Autowired
    private BasicWarehouseService basicWarehouseService;
    @Autowired
    private BasicPutgoodsService basicPutgoodsService;
    @Autowired
    private DictService dictService;
    @Autowired
    private StorageOutDetailedService storageOutDetailedService;
    @Autowired
    private OutOrderDetailedService outOrderDetailedService;
    @Autowired
    private OrderTransportService orderTransportService;
    @Autowired
    private OrderPutService orderPutService;
	@Autowired
    private BasicGoodsService goodsService;

	@Autowired
    private ReplenishmentOrderService replenishmentOrderService;

    private Lock lock = new ReentrantLock();

	/**
     * 修改卸货地址
     */
    @RequestMapping("/editAddress")
    public String editAddress(Long setLocationId,Model model) {
    	BasicAddress basicAddress = basicAddressService.getById(setLocationId);
    	model.addAttribute("set_longitude", basicAddress.getLongitude());
    	model.addAttribute("set_latitude", basicAddress.getLatitude());
        return PREFIX + "/basicAddress_edit.html";
    }

	/**
     * 计算距离
     */
    @RequestMapping("/toSelectdistance")
    public String toSelectdistance() {
        return PREFIX + "/selectdistance.html";
    }

    /**
     * 出库单确认页面
     */
    @RequestMapping("toConfirm")
    public String toConfirm(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/outOrderConfirm.html";
    }

    /**
     * 出库单打印页面
     */
    @RequestMapping("toPrint")
    public String toPrint(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/outOrderPrint.html";
    }

    /**
     * 查询单位列表
     */
    @ResponseBody
    @RequestMapping("/getPrintlist")
    public LayuiPageInfo getPrintlist(OutOrderParam outOrderParam,String condition ) {
    	User user = userService.getcurrentUser();
    	outOrderParam.setDeptId(user.getDeptId());
        return this.outOrderService.PrintlistPageBySpec(outOrderParam,condition,user.getOperateId());
    }

    /**
     * 批量打印先飞出库单  页面
     */
    @RequestMapping("print")
    public String print(StorageOutParam storageOutParam,Model model) {
		String getUnit = storageOutParam.getGetUnit();
		String getLocation = storageOutParam.getGetLocation();
		//解决参数中的 英文括号
    	if (getUnit!=null&&getUnit!="") {
    		getUnit = getUnit.replace("& #40;", "(");
    		getUnit = getUnit.replace("& #41;", ")");
    		storageOutParam.setGetUnit(getUnit);
		}
    	if (getLocation!=null&&getLocation!="") {
    		getLocation = getLocation.replace("& #40;", "(");
    		getLocation = getLocation.replace("& #41;", ")");
    		storageOutParam.setGetLocation(getLocation);
		}
    	model.addAttribute("storageOutParam", storageOutParam);
        return PREFIX + "/print.html";
    }

    /**
     * 批量打印出库单  页面
     */
    @RequestMapping("prints")
    public String prints(StorageOutParam storageOutParam,Model model) {
		String getUnit = storageOutParam.getGetUnit();
		String getLocation = storageOutParam.getGetLocation();
		//解决参数中的 英文括号
    	if (getUnit!=null&&getUnit!="") {
    		getUnit = getUnit.replace("& #40;", "(");
    		getUnit = getUnit.replace("& #41;", ")");
    		storageOutParam.setGetUnit(getUnit);
		}
    	if (getLocation!=null&&getLocation!="") {
    		getLocation = getLocation.replace("& #40;", "(");
    		getLocation = getLocation.replace("& #41;", ")");
    		storageOutParam.setGetLocation(getLocation);
		}
    	model.addAttribute("storageOutParam", storageOutParam);
        return PREFIX + "/prints.html";
    }

    /**
     * 批量打印销售单  页面
     */
    @RequestMapping("printQljhd")
    public String printQljhd(StorageOutParam storageOutParam,Model model,String outCustomerName) {
		String getUnit = storageOutParam.getGetUnit();
		String getLocation = storageOutParam.getGetLocation();
		//解决参数中的 英文括号
    	if (getUnit!=null&&getUnit!="") {
    		getUnit = getUnit.replace("& #40;", "(");
    		getUnit = getUnit.replace("& #41;", ")");
    		storageOutParam.setGetUnit(getUnit);
		}
    	if (getLocation!=null&&getLocation!="") {
    		getLocation = getLocation.replace("& #40;", "(");
    		getLocation = getLocation.replace("& #41;", ")");
    		storageOutParam.setGetLocation(getLocation);
		}
    	if (outCustomerName!=null&&outCustomerName!="") {
    		outCustomerName = outCustomerName.replace("& #40;", "(");
    		outCustomerName = outCustomerName.replace("& #41;", ")");
		}
    	model.addAttribute("storageOutParam", storageOutParam);
    	model.addAttribute("outCustomerName", outCustomerName);
        return PREFIX + "/printQljhd.html";
    }

    /**
     * 查询
     */
    @ResponseBody
    @RequestMapping("/getPrintstorageOut")
    public OutOrderResult getPrintstorageOut(OutOrderParam outOrderParam) {
    	User user = userService.getcurrentUser();
    	OutOrderResult r = outOrderService.getPrintstorageOut(outOrderParam);
    	r.setCreateUserName(user.getName());
    	return r;
    }

    /**
     * 查询
     */
    @ResponseBody
    @RequestMapping("/getPrintstorageOutDetailed")
    public List<OutOrderDetailedResult> getPrintstorageOutDetailed(String  detailedOutNumber) {
        OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
        outOrderDetailedParam.setDetailedOutNumber(detailedOutNumber);
        List<OutOrderDetailedResult> list = outOrderDetailedService.findListBySpec(outOrderDetailedParam);
        List<OutOrderDetailedResult> list2 = new ArrayList<OutOrderDetailedResult>();
        List<OutOrderDetailedResult> list3 = new ArrayList<OutOrderDetailedResult>();
        for (int i = 0; i < list.size(); i++) {
        	list3.add(list.get(i));
        	if(list3.size()==10) {
        		OutOrderDetailedResult r = new OutOrderDetailedResult();
        		r.setList(list3);
        		list2.add(r);
        		list3 = new ArrayList<OutOrderDetailedResult>();
        	}
		}
        if(list3.size()>0) {
    		OutOrderDetailedResult r = new OutOrderDetailedResult();
    		r.setList(list3);
    		list2.add(r);
        }
    	return list2;
    }

    /**
     * 上传excel
     */
	@RequestMapping(value = "/importExceNewmethodl" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl(@RequestPart("file") MultipartFile file,  OutOrderParam outOrderParam)  {
		ResponseData data = new ResponseData();
		lock.lock();//获取锁
		try {
			data = outOrderService.getExceldata(file,outOrderParam,data);//处理导入数据
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }
    @RequestMapping(value = "/importExceNewmethodlLY" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodlLY(@RequestPart("file") MultipartFile file,  OutOrderParam outOrderParam)  {
        ResponseData data = new ResponseData();
        lock.lock();//获取锁
        try {
            data = outOrderService.getExceldataLY(file,outOrderParam,data);//处理导入数据
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }
        return data;
    }

    /**
     * 上传excel
     * 恒安
     */
	@RequestMapping(value = "/importExceNewmethodl_ha" , method = {RequestMethod.POST} )
    @ResponseBody
    public ResponseData importExceNewmethodl_ha(@RequestPart("file") MultipartFile file,  OutOrderParam outOrderParam)  {
		ResponseData data = new ResponseData();
		lock.lock();//获取锁
		try {
			data = outOrderService.getExceldata_ha(file,outOrderParam,data);//处理导入数据
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }

    /**
     * 导出Excel
     */
    @RequestMapping("/exportExcelBySpec")
    public void exportExcelBySpec(HttpServletResponse response, OutOrderParam outOrderParam,String startTime,String endTime,String startTime2,String endTime2) throws IOException {
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		outOrderParam.setCreateUserName("'"+startTime+"' and '"+endTime+"'");
		}
    	if (ToolUtil.isNotEmpty(startTime2) && ToolUtil.isNotEmpty(endTime2)) {
    		outOrderParam.setFinishOutUserName("'"+startTime2+"' and '"+endTime2+"'");
		}
        Workbook wb = outOrderService.exportToExcel(outOrderParam);
        OutputStream output = response.getOutputStream();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(("Outbound Order Information" + ".xlsx").getBytes(), "iso-8859-1"));
        wb.write(output);
        output.close();
    }

    /**
     * 批量提交
     */
    @RequestMapping("/submits")
    @ResponseBody
    public ResponseData submits(@RequestParam("ids") Long[] ids) {
    	ResponseData data = new ResponseData();
    	data.setSuccess(true);
        OutOrderParam param = new OutOrderParam();
        User user  = userService.getcurrentUser();
		lock.lock();//获取锁
		try {
	        for (Long id : ids) {
	            OutOrder outOrder = outOrderService.getById(id);
	            if (!"PENDING_SUBMIT".equals(outOrder.getOutOrderStatus())&&!"REVOKED".equals(outOrder.getOutOrderStatus())) {
					continue;
				}
                OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
                outOrderDetailedParam.setDetailedOutNumber(outOrder.getOutOrderNumber());
                List<OutOrderDetailedResult> list = outOrderDetailedService.findListBySpec(outOrderDetailedParam);
                if (list.size()==0) {
                    data.setSuccess(false);
                    data.setMessage("Please add product details first");
                    return data;
                }
				//提交时间
				outOrder.setSubmitTime(new Date());
				//提交人名称
				outOrder.setSubmitterName(user.getName());
				BasicCustomer basicCustomer = basicCustomerService.getById(outOrder.getOutCustomerId());
	            if(ToolUtil.isNotEmpty(basicCustomer.getOutorderconfirm()) && basicCustomer.getOutorderconfirm().equals("是")) {
					storageOutDetailedService.checkStock(outOrder,data);//校验库存
					if(!data.getSuccess()){
						return data;
					}
				} else {
					storageOutDetailedService.outSingle(outOrder,data);//生成拣货单
					if(!data.getSuccess()){
						return data;
					}

					StorageOutParam storageOutParam = new StorageOutParam();
					storageOutParam.setStorageOutNumber(outOrder.getCustomerNumber());
					StorageOutResult storageOutResult = storageOutService.findBySpec(storageOutParam);

					List<StorageOutResult> listr = new ArrayList<StorageOutResult>();
					listr.add(storageOutResult);
					data = storageOutDetailedService.recommend(listr);//出库推荐库位 （~  . ~  ）***
					if (!data.getSuccess()) {
						return data;
					}
				}

				if(outOrder.getOutWay().equals("配送")){
					ToolUtil.copyProperties(outOrder,param);
					orderTransportService.outUpdateTransport(param);
					OrderTransportParam orderTransportParam = new OrderTransportParam();
					orderTransportParam.setCustomerOrder(param.getCustomerNumber());
					OrderTransportResult orderTransportResult = orderTransportService.findBySpec(orderTransportParam,null);
					if(orderTransportResult != null) {
						orderTransportService.auditorder(orderTransportResult.getId());
					}
				}
                param = new OutOrderParam();
                outOrder = new OutOrder();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }

	/**
     * 批量提交
     */
    @RequestMapping("/submitsHshn")
    @ResponseBody
    public ResponseData submitsHshn(@RequestParam("ids") Long[] ids) {
    	ResponseData data = new ResponseData();
    	data.setSuccess(true);
        OutOrderParam param = new OutOrderParam();
        User user  = userService.getcurrentUser();
		lock.lock();//获取锁
		try {
	        for (Long id : ids) {
	            OutOrder outOrder = outOrderService.getById(id);
	            if (!"PENDING_SUBMIT".equals(outOrder.getOutOrderStatus())&&!"REVOKED".equals(outOrder.getOutOrderStatus())) {
					continue;
				}
                OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
                outOrderDetailedParam.setDetailedOutNumber(outOrder.getOutOrderNumber());
                List<OutOrderDetailedResult> list = outOrderDetailedService.findListBySpec(outOrderDetailedParam);
                if (list.size()==0) {
                    data.setSuccess(false);
                    data.setMessage("Please add product details first");
                    return data;
                }
				//提交时间
				outOrder.setSubmitTime(new Date());
				//提交人名称
				outOrder.setSubmitterName(user.getName());
				BasicCustomer basicCustomer = basicCustomerService.getById(outOrder.getOutCustomerId());
	            if(ToolUtil.isNotEmpty(basicCustomer.getOutorderconfirm()) && basicCustomer.getOutorderconfirm().equals("是")) {
					storageOutDetailedService.checkStock(outOrder,data);//校验库存
					if(!data.getSuccess()){
						return data;
					}
				} else {
					storageOutDetailedService.outSingleHSHN(outOrder,data);//生成拣货单
					if(!data.getSuccess()){
						return data;
					}

					if(data.getCode( ) == 7527){
						Map<String,List<Map<String,String>>> mapData  = (Map<String, List<Map<String, String>>>)data.getData();
						List<Map<String, String>> kcbzlist = (List<Map<String, String>>)mapData.get("kcbzlist");
						List<Map<String, String>> bhlist = (List<Map<String, String>>)mapData.get("bhlist");

						for (Map<String, String> stringObjectMap : bhlist) {
							replenishmentOrderService.generateReplenishmentOrder(stringObjectMap.get("goodsNumber"),stringObjectMap.get("goodsCount"));
						}
					}
					StorageOutParam storageOutParam = new StorageOutParam();
					storageOutParam.setStorageOutNumber(outOrder.getCustomerNumber());
					StorageOutResult storageOutResult = storageOutService.findBySpec(storageOutParam);
					if(ToolUtil.isEmpty(storageOutResult)){
						continue;
					}
					List<StorageOutResult> listr = new ArrayList<StorageOutResult>();
					listr.add(storageOutResult);
					data = storageOutDetailedService.recommend(listr);//出库推荐库位 （~  . ~  ）***
					if (!data.getSuccess()) {
						return data;
					}
				}

				if(outOrder.getOutWay().equals("配送")){
					ToolUtil.copyProperties(outOrder,param);
					orderTransportService.outUpdateTransport(param);
					OrderTransportParam orderTransportParam = new OrderTransportParam();
					orderTransportParam.setCustomerOrder(param.getCustomerNumber());
					OrderTransportResult orderTransportResult = orderTransportService.findBySpec(orderTransportParam,null);
					if(orderTransportResult != null) {
						orderTransportService.auditorder(orderTransportResult.getId());
					}
				}
                param = new OutOrderParam();
                outOrder = new OutOrder();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }

	/**
	 * 批量提交【武汉】
	 * @param ids
	 * @return
	 */
	@RequestMapping("/submitsWhHshn")
    @ResponseBody
    public ResponseData submitsWhHshn(@RequestParam("ids") Long[] ids) {
    	ResponseData data = new ResponseData();
    	data.setSuccess(true);
        OutOrderParam param = new OutOrderParam();
        User user  = userService.getcurrentUser();
		lock.lock();//获取锁
		try {
	        for (Long id : ids) {
	            OutOrder outOrder = outOrderService.getById(id);
	            if (!"PENDING_SUBMIT".equals(outOrder.getOutOrderStatus())&&!"REVOKED".equals(outOrder.getOutOrderStatus())) {
					continue;
				}
                OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
                outOrderDetailedParam.setDetailedOutNumber(outOrder.getOutOrderNumber());
                List<OutOrderDetailedResult> list = outOrderDetailedService.findListBySpec(outOrderDetailedParam);
                if (list.size()==0) {
                    data.setSuccess(false);
                    data.setMessage("请先添加商品明细");
                    return data;
                }
				//提交时间
				outOrder.setSubmitTime(new Date());
				//提交人名称
				outOrder.setSubmitterName(user.getName());
				BasicCustomer basicCustomer = basicCustomerService.getById(outOrder.getOutCustomerId());
	            if(ToolUtil.isNotEmpty(basicCustomer.getOutorderconfirm()) && basicCustomer.getOutorderconfirm().equals("是")) {
					storageOutDetailedService.checkStock(outOrder,data);//校验库存
					if(!data.getSuccess()){
						return data;
					}
				} else {
					storageOutDetailedService.outSingleWhHSHN(outOrder,data);//生成拣货单
					if(!data.getSuccess()){
						return data;
					}


					StorageOutParam storageOutParam = new StorageOutParam();
					storageOutParam.setStorageOutNumber(outOrder.getCustomerNumber());
					StorageOutResult storageOutResult = storageOutService.findBySpec(storageOutParam);
					if(ToolUtil.isEmpty(storageOutResult)){
						continue;
					}
					List<StorageOutResult> listr = new ArrayList<StorageOutResult>();
					listr.add(storageOutResult);
					data = storageOutDetailedService.recommend(listr);//出库推荐库位 （~  . ~  ）***
					if (!data.getSuccess()) {
						return data;
					}
				}

				if(outOrder.getOutWay().equals("配送")){
					ToolUtil.copyProperties(outOrder,param);
					orderTransportService.outUpdateTransport(param);
					OrderTransportParam orderTransportParam = new OrderTransportParam();
					orderTransportParam.setCustomerOrder(param.getCustomerNumber());
					OrderTransportResult orderTransportResult = orderTransportService.findBySpec(orderTransportParam,null);
					if(orderTransportResult != null) {
						orderTransportService.auditorder(orderTransportResult.getId());
					}
				}
                param = new OutOrderParam();
                outOrder = new OutOrder();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }

    /**
     * 去 确认页面
     */
    @RequestMapping("toConfirm1")
    public String toConfirm1(Model model) {
        return PREFIX + "/confirm.html";
    }

    @Autowired
    private TransportReceiptService transportReceiptService;

    /**
     * 确认
     */
    @RequestMapping("/confirm1")
    @ResponseBody
    public ResponseData confirm1(OutOrderParam orderParam) {
    	ResponseData data = new ResponseData();
    	data.setSuccess(true);
        User user  = userService.getcurrentUser();
		lock.lock();//获取锁
		try {
			outOrderService.update(orderParam);
            OutOrder outOrder = outOrderService.getById(orderParam.getId());
	    	//更新货运订单 收货地址信息
	    	OrderTransportParam orderTransportParam2 = new OrderTransportParam();
	    	orderTransportParam2.setGetLocationId(outOrder.getGetLocationId());
	    	orderTransportParam2.setGetLocation(orderParam.getGetLocation());
	    	orderTransportParam2.setKilometer(orderParam.getKilometer());
	    	orderTransportService.updateBySpec2(orderTransportParam2);

	    	//更新回传表 未回传地址
	    	TransportReceiptParam transportReceiptParam = new TransportReceiptParam();
	    	transportReceiptParam.setGetLocationid(outOrder.getGetLocationId());
	    	transportReceiptParam.setTstate("NOT_RETURNED");
	    	transportReceiptParam.setGetLocation(orderParam.getGetLocation());
	    	transportReceiptService.updateBySpec(transportReceiptParam);

	    	BasicAddressParam basicAddressParam = new BasicAddressParam();
	    	basicAddressParam.setId(Integer.parseInt(outOrder.getGetLocationId().toString()));
	    	basicAddressParam.setAddress(orderParam.getGetLocation());
	    	basicAddressParam.setKilometer(orderParam.getKilometer());
	    	basicAddressParam.setLongitude(orderParam.getLongitude());
	    	basicAddressParam.setLatitude(orderParam.getLatitude());
	        this.basicAddressService.update(basicAddressParam);

            if ("PENDING_CONFIRMATION".equals(outOrder.getOutOrderStatus())) {
                OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
                outOrderDetailedParam.setDetailedOutNumber(outOrder.getOutOrderNumber());
                List<OutOrderDetailedResult> list = outOrderDetailedService.findListBySpec(outOrderDetailedParam);
                if (list.size()==0) {
                	data.setSuccess(false);
                	data.setMessage("Please add product details first");
                	return data;
                }
                //提交时间
                outOrder.setSubmitTime(new Date());
                //提交人名称
                outOrder.setSubmitterName(user.getName());
                //确认人名称
                outOrder.setExamineName(user.getName());
                //确认时间
                outOrder.setExamineTime(new Date());
                storageOutDetailedService.outSingle(outOrder,data);//生成拣货单
                if(!data.getSuccess()){
                	return data;
                }

                StorageOutParam storageOutParam = new StorageOutParam();
                storageOutParam.setStorageOutNumber(outOrder.getCustomerNumber());
                StorageOutResult storageOutResult = storageOutService.findBySpec(storageOutParam);
                List<StorageOutResult> listr = new ArrayList<StorageOutResult>();
                listr.add(storageOutResult);
                data = storageOutDetailedService.recommend(listr);//出库推荐库位 （~  . ~  ）***
                if (!data.getSuccess()) {
                	return data;
                }
                outOrder = new OutOrder();
            }
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }

    /**
     * 批量确认
     */
    @RequestMapping("/confirm")
    @ResponseBody
    public ResponseData confirm(@RequestParam("ids") Long[] ids) {
    	ResponseData data = new ResponseData();
    	data.setSuccess(true);
        User user  = userService.getcurrentUser();
		lock.lock();//获取锁
		try {
	        for (Long id : ids) {
	            OutOrder outOrder = outOrderService.getById(id);
	            if (!"PENDING_CONFIRMATION".equals(outOrder.getOutOrderStatus())) {
					continue;
				}
                OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
                outOrderDetailedParam.setDetailedOutNumber(outOrder.getOutOrderNumber());
                List<OutOrderDetailedResult> list = outOrderDetailedService.findListBySpec(outOrderDetailedParam);
                if (list.size()==0) {
                    data.setSuccess(false);
                    data.setMessage("Please add product details first");
                    return data;
                }
				//提交时间
				outOrder.setSubmitTime(new Date());
				//提交人名称
				outOrder.setSubmitterName(user.getName());
				//确认人名称
				outOrder.setExamineName(user.getName());
				//确认时间
				outOrder.setExamineTime(new Date());
				storageOutDetailedService.outSingle(outOrder,data);//生成拣货单
				if(!data.getSuccess()){
					return data;
				}

				StorageOutParam storageOutParam = new StorageOutParam();
				storageOutParam.setStorageOutNumber(outOrder.getCustomerNumber());
				StorageOutResult storageOutResult = storageOutService.findBySpec(storageOutParam);
				List<StorageOutResult> listr = new ArrayList<StorageOutResult>();
				listr.add(storageOutResult);
				data = storageOutDetailedService.recommend(listr);//出库推荐库位 （~  . ~  ）***
				if (!data.getSuccess()) {
					return data;
				}
                outOrder = new OutOrder();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }

    /**
     * 批量提交
     */
    @RequestMapping("/submits2")
    @ResponseBody
    public ResponseData submits2(@RequestParam("ids") Long[] ids) {
    	ResponseData data = new ResponseData();
    	data.setSuccess(true);
        OutOrderParam param = new OutOrderParam();
        User user  = userService.getcurrentUser();
		lock.lock();//获取锁
		try {
	        for (Long id : ids) {
	            OutOrder outOrder = outOrderService.getById(id);
	            BasicCustomer c = basicCustomerService.getById(outOrder.getOutCustomerId());
	            if (!"PENDING_SUBMIT".equals(outOrder.getOutOrderStatus())&&!"REVOKED".equals(outOrder.getOutOrderStatus())) {
					continue;
				}
                OutOrderDetailedParam outOrderDetailedParam = new OutOrderDetailedParam();
                outOrderDetailedParam.setDetailedOutNumber(outOrder.getOutOrderNumber());
                List<OutOrderDetailedResult> list = outOrderDetailedService.findListBySpec(outOrderDetailedParam);
                if (list.size()==0) {
                    data.setSuccess(false);
                    data.setMessage("Please add product details first");
                    return data;
                }
				//提交时间
				outOrder.setSubmitTime(new Date());
				//提交人名称
				outOrder.setSubmitterName(user.getName());
				storageOutDetailedService.outSingle(outOrder,data);//生成拣货单
				if(!data.getSuccess()){
					return data;
				}

				StorageOutParam storageOutParam = new StorageOutParam();
				storageOutParam.setStorageOutNumber(outOrder.getCustomerNumber());
				StorageOutResult storageOutResult = storageOutService.findBySpec(storageOutParam);
				List<StorageOutResult> listr = new ArrayList<StorageOutResult>();
				listr.add(storageOutResult);
				data = storageOutDetailedService.recommend(listr);//出库推荐库位 （~  . ~  ）***
				if (!data.getSuccess()) {
					return data;
				}

				if(outOrder.getOutWay().equals("配送")){
			        if(c != null && ToolUtil.isNotEmpty(c.getWmsAddtms())&&c.getWmsAddtms().equals("1")) {
			        	ToolUtil.copyProperties(outOrder,param);
			        	orderTransportService.outUpdateTransport(param);
			        	OrderTransportParam orderTransportParam = new OrderTransportParam();
			        	orderTransportParam.setCustomerOrder(param.getCustomerNumber());
			        	OrderTransportResult orderTransportResult = orderTransportService.findBySpec(orderTransportParam,null);
			        	if(orderTransportResult != null) {
			        		orderTransportService.auditorder(orderTransportResult.getId());
			        	}
			        }
				}
                param = new OutOrderParam();
                outOrder = new OutOrder();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }

    /**
     * 跳转到主页面
     */
    @RequestMapping("")
    public String index(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/outOrder.html";
    }

    /**
     * 出库订单查询页面
     */
    @RequestMapping("toQuery")
    public String toQuery(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/outOrderQuery.html";
    }

    /**
     * 出库订单查询页面云仓
     */
    @RequestMapping("toQueryTool")
    public String toQueryTool(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/outOrderQueryTool.html";
    }

    /**
     * 新增页面
     */
    @RequestMapping("/add")
    public String add(Model model) {
        preViewData(model);
        return PREFIX + "/outOrder_add.html";
    }

    /**
     * 编辑页面
     */
    @RequestMapping("/edit")
    public String edit(@RequestParam("id") Long id, Model model) {
        OutOrder outOrder = this.outOrderService.getById(id);
        OrderTransportParam orderTransportParam = new OrderTransportParam();
        orderTransportParam.setCustomerOrder(outOrder.getCustomerNumber());
        OrderTransportResult transportResult = orderTransportService.findBySpec(orderTransportParam,null);
        model.addAttribute("transportResult", transportResult);
        preViewData(model);
        return PREFIX + "/outOrder_edit.html";
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel")
    public String toimportExcel(Model model) {
    	preViewData(model);
        return PREFIX + "/outOrder_import.html";
    }
	/**
	 * 导入页面
	 */
	@RequestMapping("/toimportExcelDD")
	public String toimportExcelDD(Model model) {
		preViewData(model);
		return PREFIX + "/outOrder_importDD.html";
	}

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel_ql")
    public String toimportExcel_ql(Model model) {
    	preViewData(model);
        return PREFIX + "/outOrder_import_ql.html";
    }

    /**
     * 导入页面
     */
    @RequestMapping("/toimportExcel_ha")
    public String toimportExcel_ha(Model model) {
    	preViewData(model);
        return PREFIX + "/outOrder_import_ha.html";
    }

    /**
     * 跳转到审核页面list
     */
    @RequestMapping("toExamine")
    public String toExamine() {
        return PREFIX + "/outExamine.html";
    }

    /**
     * 审核页面
     */
    @RequestMapping("/toAudit")
    public String toAudit(OutOrderParam outOrderParam, Model model) {
        OutOrder outOrder = outOrderService.getById(outOrderParam.getId());
        model.addAttribute("outOrder", outOrder);
        return PREFIX + "/outOrder_audit.html";
    }

    @Autowired
    private StorageOutService storageOutService;

    /**
     * 批量发起
     */
    @RequestMapping("/btnLaunch")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class)
    public ResponseData btnLaunch(@RequestParam("ids") Long[] ids) {
        for (Long id :ids) {
            OutOrder outOrder = outOrderService.getById(id);
            outOrder.setOutOrderStatus("PENDING_SUBMIT");
            OutOrderParam outOrderParam = new OutOrderParam();
            ToolUtil.copyProperties(outOrder,outOrderParam);
            outOrderService.update(outOrderParam);
        }
        return ResponseData.success();
    }

    /**
     * 发起
     */
    @RequestMapping("/launch")
    @ResponseBody
    public ResponseData launch(OutOrderParam outOrderParam) {
    	ResponseData data = new ResponseData();
        OutOrder outOrder = outOrderService.getById(outOrderParam.getId());
        outOrderParam.setCustomerNumber(outOrder.getCustomerNumber());
        OutOrderResult orderResult = outOrderService.findBySpec(outOrderParam,null);
        if (orderResult!=null) {
    		data.setSuccess(false);
    		data.setMessage("Customer tracking number already exists");
    		return data;
		}
        outOrder.setOutOrderStatus("PENDING_SUBMIT");
        ToolUtil.copyProperties(outOrder,outOrderParam);
        outOrderService.update(outOrderParam);
        return ResponseData.success();
    }

    /**
     * 撤回
     */
    @RequestMapping("/revoke")
    @ResponseBody
    public ResponseData revoke(OutOrderParam outOrderParam) {
    	ResponseData data = new ResponseData();
        OutOrder outOrder = outOrderService.getById(outOrderParam.getId());
        if ("PENDING_SHIPMENT".equals(outOrder.getOutOrderStatus())|| "SHIPPED_OUT".equals(outOrder.getOutOrderStatus())|| "PENDING_CONFIRMATION".equals(outOrder.getOutOrderStatus())) {
        	data = outOrderService.revokeS(outOrder,data);
		} else {
			data.setSuccess(false);
		}
        return data;
    }

    /**
     * 撤回
     * 云仓
     */
    @RequestMapping("/revoketool")
    @ResponseBody
    public ResponseData revoketool(OutOrderParam outOrderParam) {
    	ResponseData data = new ResponseData();
        OutOrder outOrder = outOrderService.getById(outOrderParam.getId());
        if ("PENDING_SHIPMENT".equals(outOrder.getOutOrderStatus())|| "SHIPPED_OUT".equals(outOrder.getOutOrderStatus())) {
        	data = outOrderService.revoketool(outOrder,data);
		} else {
			data.setSuccess(false);
		}
        return data;
    }

    /**
     * 批量作废
     * @param ids
     * @return
     */
    @RequestMapping("/cancel")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public  ResponseData cancel(@RequestParam("ids") Long[] ids){
        for (Long id :ids) {
            try {
                OutOrder outOrder = outOrderService.getById(id);
                outOrder.setOutOrderStatus("CANCELLED");
                OutOrderParam outOrderParam = new OutOrderParam();
                ToolUtil.copyProperties(outOrder,outOrderParam);
                outOrderService.update(outOrderParam);
            } catch (Exception e) {
                break;
            }
        }
        return ResponseData.success();
    }

    /**
     * 生成
     * @param storageOutParam
     * @return
     */
    @RequestMapping("/recommend")
    @ResponseBody
    public ResponseData recommend(StorageOutParam storageOutParam) {
    	ResponseData data = new ResponseData();
//    	storageOutDetailedService.recommend(storageOutParam,data);
		return data;
    }

    /**
     * 复原
     * @param storageOutParam
     * @return
     */
    @RequestMapping("/restore")
    @ResponseBody
    public ResponseData restore(StorageOutParam storageOutParam) {
    	ResponseData data = new ResponseData();
    	storageOutDetailedService.restore(storageOutParam,data);
		return data;
    }

    /**
     * 批量审核 通过
     */
    @RequestMapping("/batchVia")
    @ResponseBody
    public ResponseData batchVia(@RequestParam("ids") Long[] ids) {
    	ResponseData data = new ResponseData();
    	data.setSuccess(true);
        OutOrderParam param = new OutOrderParam();
        User user  = userService.getcurrentUser();
		lock.lock();//获取锁
		try {
	        //生成拣货单
	        for (Long id : ids) {
	            OutOrder outOrder = outOrderService.getById(id);
	            BasicCustomer c = basicCustomerService.getById(outOrder.getOutCustomerId());
	            if (!"PENDING_AUDIT".equals(outOrder.getOutOrderStatus())) {
					continue;
				}
	            outOrder.setExamineTime(new Date());//审核时间
	            outOrder.setExamineUser(user.getUserId());//审核人id
	            outOrder.setExamineName(user.getName());//审核人名称
                storageOutDetailedService.outSingle(outOrder,data);
                if(!data.getSuccess()){
                    return data;
                }
                ToolUtil.copyProperties(outOrder,param);
		        if(c != null && ToolUtil.isNotEmpty(c.getWmsAddtms())&&c.getWmsAddtms().equals("1")) {
		        	orderTransportService.outUpdateTransport(param);
		        	OrderTransportParam orderTransportParam = new OrderTransportParam();
		        	orderTransportParam.setCustomerOrder(param.getCustomerNumber());
		        	OrderTransportResult orderTransportResult = orderTransportService.findBySpec(orderTransportParam,null);
		        	if(orderTransportResult != null) {
		        		orderTransportService.auditorder(orderTransportResult.getId());
		        	}
		        }
                param = new OutOrderParam();
                outOrder = new OutOrder();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();//释放锁
		}
        return data;
    }

    /**
     * 审核出库订单
     */
    @RequestMapping("/audit")
    @ResponseBody
    public ResponseData audit(OutOrderParam outOrderParam, @RequestParam("whether") String whether) {
    	ResponseData data = new ResponseData();
        OutOrder outOrder = outOrderService.getById(outOrderParam.getId());
        BasicCustomer c = basicCustomerService.getById(outOrder.getOutCustomerId());
        if (!"PENDING_AUDIT".equals(outOrder.getOutOrderStatus())) {
        	data.setSuccess(true);
			return data;
		}
        OutOrderParam param = new OutOrderParam();
        User user  = userService.getcurrentUser();
        //审核时间
        outOrder.setExamineTime(new Date());
        //审核人id
        outOrder.setExamineUser(user.getUserId());
        //审核人名称
        outOrder.setExamineName(user.getName());
        if ("1".equals(whether)) {
            //生成拣货单
    		lock.lock();//获取锁
    		try {
                storageOutDetailedService.outSingle(outOrder,data);
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			lock.unlock();//释放锁
    		}

            ToolUtil.copyProperties(outOrder,param);
	        if(c != null && ToolUtil.isNotEmpty(c.getWmsAddtms())&&c.getWmsAddtms().equals("1")) {
	        	orderTransportService.outUpdateTransport(param);
	        	OrderTransportParam orderTransportParam = new OrderTransportParam();
	        	orderTransportParam.setCustomerOrder(param.getCustomerNumber());
	        	OrderTransportResult orderTransportResult = orderTransportService.findBySpec(orderTransportParam,null);
	        	if(orderTransportResult != null) {
	        		orderTransportService.auditorder(orderTransportResult.getId());
	        	}
	        }
        } else
            if("2".equals(whether)) {
            outOrder.setOutOrderStatus("REJECTED");
            outOrder.setReturnNote(outOrderParam.getReturnNote());
            ToolUtil.copyProperties(outOrder,param);
            outOrderService.update(param);
        }
        return data;
    }

    /**
     * 审核列表
     */
    @ResponseBody
    @RequestMapping("/examineList")
    public LayuiPageInfo examineList(OutOrderParam outOrderParam, String condition ) {
    	User user = userService.getcurrentUser();
        outOrderParam.setDeliverId(user.getDeliverId());
        outOrderParam.setDeptId(user.getDeptId());
        outOrderParam.setOutOrderStatus("examine");
        return this.outOrderService.findPageBySpec(outOrderParam,condition,user.getOperateId());
    }

    /**
     * 数据的回显
     * @param model
     */
    public void preViewData(Model model){
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));
        //结算方式
        List<DictResult> dictResultList = dictService.findByDicttypeCode2("SETTLEMENT_METHOD");
        model.addAttribute("dictResultList",dictResultList);
        //运输方式
        List<DictResult> dictResultList1 = dictService.findByDicttypeCode2("TRANSPORT");
        model.addAttribute("dictResultList1", dictResultList1);

//        List<BasicPutgoods> basicPutgoodsList = basicPutgoodsService.list();
//        model.addAttribute("basicPutgoodsList",basicPutgoodsList);

        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId, deliverId,user.getOperateId()));
    }

	@Autowired
    private DeptService deptService;

	/**
	 * 获取所属项目单号前缀
	 * @param user
	 * @return
	 */
	public String getOperateIdOrderPrefix(User user) {
		if(user.getOperateId() != null) {
			Dept dept = new Dept();
			dept.setOperateId(user.getOperateId());
			Dept resdept = deptService.findBySpec(dept);
			if(resdept != null) {
				if(ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
					return resdept.getOrderPrefix();
				} else {
					return user.getAccount().substring(0, 3);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

    /**
     * 新增接口
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(OutOrderParam outOrderParam, OrderTransportParam orderTransportParam) {
    	User user = userService.getcurrentUser();
    	ResponseData data = new ResponseData();
    	//校验客户单号 是否存在
    	if (this.orderPutService.checkCustomerOrder(outOrderParam.getCustomerNumber())) {
    		data.setSuccess(false);
    		data.setMessage("Customer tracking number already exists");
    		return data;
		} else {
    		data.setSuccess(true);
		}
        if(outOrderParam!=null){
        	String getUnit = outOrderParam.getGetUnit();
        	String getLocation = outOrderParam.getGetLocation();
        	String setUnit = outOrderParam.getSetUnit();
        	String setLocation = outOrderParam.getSetLocation();
        	//解决参数中的 英文括号
        	if (getUnit!=null&&getUnit!="") {
        		getUnit = getUnit.replace("& #40;", "(");
        		getUnit = getUnit.replace("& #41;", ")");
        		outOrderParam.setGetUnit(getUnit);
        	}
        	if (getLocation!=null&&getLocation!="") {
        		getLocation = getLocation.replace("& #40;", "(");
        		getLocation = getLocation.replace("& #41;", ")");
        		outOrderParam.setGetLocation(getLocation);
        	}
        	if (setUnit!=null&&setUnit!="") {
        		setUnit = setUnit.replace("& #40;", "(");
        		setUnit = setUnit.replace("& #41;", ")");
        		outOrderParam.setSetUnit(setUnit);
        	}
        	if (setLocation!=null&&setLocation!="") {
        		setLocation = setLocation.replace("& #40;", "(");
        		setLocation = setLocation.replace("& #41;", ")");
        		outOrderParam.setSetLocation(setLocation);
        	}
        }
        if(orderTransportParam!=null){
        	String getUnit = orderTransportParam.getGetUnit();
        	String getLocation = orderTransportParam.getGetLocation();
        	String setUnit = orderTransportParam.getSetUnit();
        	String setLocation = orderTransportParam.getSetLocation();
        	//解决参数中的 英文括号
        	if (getUnit!=null&&getUnit!="") {
        		getUnit = getUnit.replace("& #40;", "(");
        		getUnit = getUnit.replace("& #41;", ")");
        		orderTransportParam.setGetUnit(getUnit);
        	}
        	if (getLocation!=null&&getLocation!="") {
        		getLocation = getLocation.replace("& #40;", "(");
        		getLocation = getLocation.replace("& #41;", ")");
        		orderTransportParam.setGetLocation(getLocation);
        	}
        	if (setUnit!=null&&setUnit!="") {
        		setUnit = setUnit.replace("& #40;", "(");
        		setUnit = setUnit.replace("& #41;", ")");
        		orderTransportParam.setSetUnit(setUnit);
        	}
        	if (setLocation!=null&&setLocation!="") {
        		setLocation = setLocation.replace("& #40;", "(");
        		setLocation = setLocation.replace("& #41;", ")");
        		orderTransportParam.setSetLocation(setLocation);
        	}
        }
        //部门id
        Long deptId = user.getDeptId();
        if (deptId != null){
            outOrderParam.setDeptId(deptId);
        }
        //交付id
        Long DeliverId = user.getDeliverId();
        if (DeliverId != null){
            outOrderParam.setDeliverId(DeliverId);
        }
        //客户id
        Object outCustomerId = outOrderParam.getOutCustomerId();
        BasicCustomer basicCustomer = new BasicCustomer();
        if(outCustomerId != null){
            basicCustomer = basicCustomerService.getById(Integer.parseInt(outCustomerId.toString()));
            outOrderParam.setOutCustomerName(basicCustomer.getCustomerName());
        }
        //仓库id
        Object outStorehouseId = outOrderParam.getOutStorehouseId();
        if (outStorehouseId != null){
            BasicWarehouse basicWarehouse = basicWarehouseService.getById(Integer.parseInt(outStorehouseId.toString()));
            outOrderParam.setStorehouseName(basicWarehouse.getWarehouseName());
        }
        outOrderParam.setOutOrderStatus("PENDING_SUBMIT");
        //获取制单人姓名
        outOrderParam.setCreateUserName(user.getName());
		String trayCode = getOperateIdOrderPrefix(user);
        OutOrder outOrder = this.outOrderService.findByTheLastOne();
        if (outOrder != null){
            outOrderParam.setOutOrderNumber(trayCode+"-"+"CK-"+DateUtil.getDateBch()+"-"+(outOrder.getId()+1));
        }else {
            outOrderParam.setOutOrderNumber(trayCode+"-"+"CK-"+DateUtil.getDateBch()+"-"+"1");
        }
        this.outOrderService.add(outOrderParam);
        if(basicCustomer != null && ToolUtil.isNotEmpty(basicCustomer.getWmsAddtms())&&basicCustomer.getWmsAddtms().equals("1")) {
        	BasicAddress basicAddress = basicAddressService.getById(outOrderParam.getGetLocationId());
        	outOrderParam.setKilometer(basicAddress.getKilometer());
        	orderTransportService.outAddTransport(outOrderParam, orderTransportParam);

        	if(ToolUtil.isNotEmpty(outOrderParam.getGetPeople()) || ToolUtil.isNotEmpty(outOrderParam.getGetTel())) {
        		BasicAddressParam addressParam = new BasicAddressParam();
        		addressParam.setId(Integer.parseInt(outOrderParam.getGetLocationId().toString()));
        		if(ToolUtil.isNotEmpty(outOrderParam.getGetPeople())) {
        			addressParam.setContacts(outOrderParam.getGetPeople());
        		}
        		if(ToolUtil.isNotEmpty(outOrderParam.getGetTel())) {
        			addressParam.setTel(outOrderParam.getGetTel());
        		}
        		basicAddressService.update(addressParam);
        	}
        }
        return ResponseData.success();
    }

    @Autowired
    private BasicAddressService basicAddressService;

    /**
     * 下载出库订单模板
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelTemplate")
    public void downloadExcelTemplate(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/outOrder.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("Outbound Order Template" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载出库订单模板
     * 恒安
     * @throws ServletException , IOException
     */
    @RequestMapping("downloadExcelTemplate_ha")
    public void downloadExcelTemplate_ha(HttpServletRequest request,HttpServletResponse response) throws ServletException ,IOException {
        String path = "assets/excel/outOrder_ha.xlsx";
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(path);
            OutputStream  outputStream = response.getOutputStream();
            //设置下载的文件类型
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //设置下载文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(("出库订单恒安模板" + ".xlsx").getBytes(), "iso-8859-1"));
            IOUtils.copy(inputStream, outputStream);
            outputStream.flush();
            inputStream.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 编辑接口
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(OutOrderParam outOrderParam, OrderTransportParam orderTransportParam) {
    	ResponseData data = new ResponseData();
    	//校验客户单号 是否存在
    	OutOrder outOrder = this.outOrderService.getById(outOrderParam.getId());
    	if (!outOrder.getCustomerNumber().equals(outOrderParam.getCustomerNumber())) {
        	if (this.orderPutService.checkCustomerOrder(outOrderParam.getCustomerNumber())) {
        		data.setSuccess(false);
        		data.setMessage("Customer tracking number already exists");
        		return data;
    		} else {
        		data.setSuccess(true);
    		}
		}

        Object outCustomerId = outOrderParam.getOutCustomerId();
        if(outOrderParam!=null){
        	String getUnit = outOrderParam.getGetUnit();
        	String getLocation = outOrderParam.getGetLocation();
        	String setUnit = outOrderParam.getSetUnit();
        	String setLocation = outOrderParam.getSetLocation();
        	//解决参数中的 英文括号
        	if (getUnit!=null&&getUnit!="") {
        		getUnit = getUnit.replace("& #40;", "(");
        		getUnit = getUnit.replace("& #41;", ")");
        		outOrderParam.setGetUnit(getUnit);
        	}
        	if (getLocation!=null&&getLocation!="") {
        		getLocation = getLocation.replace("& #40;", "(");
        		getLocation = getLocation.replace("& #41;", ")");
        		outOrderParam.setGetLocation(getLocation);
        	}
        	if (setUnit!=null&&setUnit!="") {
        		setUnit = setUnit.replace("& #40;", "(");
        		setUnit = setUnit.replace("& #41;", ")");
        		outOrderParam.setSetUnit(setUnit);
        	}
        	if (setLocation!=null&&setLocation!="") {
        		setLocation = setLocation.replace("& #40;", "(");
        		setLocation = setLocation.replace("& #41;", ")");
        		outOrderParam.setSetLocation(setLocation);
        	}
        }
        if(orderTransportParam!=null){
        	String getUnit = orderTransportParam.getGetUnit();
        	String getLocation = orderTransportParam.getGetLocation();
        	String setUnit = orderTransportParam.getSetUnit();
        	String setLocation = orderTransportParam.getSetLocation();
        	//解决参数中的 英文括号
        	if (getUnit!=null&&getUnit!="") {
        		getUnit = getUnit.replace("& #40;", "(");
        		getUnit = getUnit.replace("& #41;", ")");
        		orderTransportParam.setGetUnit(getUnit);
        	}
        	if (getLocation!=null&&getLocation!="") {
        		getLocation = getLocation.replace("& #40;", "(");
        		getLocation = getLocation.replace("& #41;", ")");
        		orderTransportParam.setGetLocation(getLocation);
        	}
        	if (setUnit!=null&&setUnit!="") {
        		setUnit = setUnit.replace("& #40;", "(");
        		setUnit = setUnit.replace("& #41;", ")");
        		orderTransportParam.setSetUnit(setUnit);
        	}
        	if (setLocation!=null&&setLocation!="") {
        		setLocation = setLocation.replace("& #40;", "(");
        		setLocation = setLocation.replace("& #41;", ")");
        		orderTransportParam.setSetLocation(setLocation);
        	}
        }
        BasicCustomer basicCustomer = new BasicCustomer();
        if(outCustomerId != null){
            basicCustomer = basicCustomerService.getById(Integer.parseInt(outCustomerId.toString()));
            outOrderParam.setOutCustomerName(basicCustomer.getCustomerName());
        }
        Object outStorehouseId = outOrderParam.getOutStorehouseId();
        if (outStorehouseId != null){
            BasicWarehouse basicWarehouse = basicWarehouseService.getById(Integer.parseInt(outStorehouseId.toString()));
            outOrderParam.setStorehouseName(basicWarehouse.getWarehouseName());
        }
        BasicAddress basicAddress = basicAddressService.getById(outOrderParam.getGetLocationId());
        outOrderParam.setKilometer(basicAddress.getKilometer());
        outOrderParam.setUpdateUserName(userService.getcurrentUser().getName());
        this.outOrderService.update(outOrderParam);

        if(basicCustomer != null && ToolUtil.isNotEmpty(basicCustomer.getWmsAddtms())&&basicCustomer.getWmsAddtms().equals("1")) {
        	orderTransportService.outEditTransport(outOrderParam, orderTransportParam);
        	if(ToolUtil.isNotEmpty(outOrderParam.getGetPeople()) || ToolUtil.isNotEmpty(outOrderParam.getGetTel())) {
        		BasicAddressParam addressParam = new BasicAddressParam();
        		addressParam.setId(Integer.parseInt(outOrderParam.getGetLocationId().toString()));
        		if(ToolUtil.isNotEmpty(outOrderParam.getGetPeople())) {
        			addressParam.setContacts(outOrderParam.getGetPeople());
        		}
        		if(ToolUtil.isNotEmpty(outOrderParam.getGetTel())) {
        			addressParam.setTel(outOrderParam.getGetTel());
        		}
        		basicAddressService.update(addressParam);
        	}
        }
        return ResponseData.success();
    }

    /**
     * 删除接口
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(OutOrderParam outOrderParam) {
        this.outOrderService.delete(outOrderParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(OutOrderParam outOrderParam) {
        OutOrder detail = this.outOrderService.getById(outOrderParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查看详情接口
     */
    @RequestMapping("/detail2")
    @ResponseBody
    public ResponseData detail2(OutOrderParam outOrderParam) {
        OutOrder detail = this.outOrderService.getById(outOrderParam.getId());
        BasicAddress basicAddress2 = basicAddressService.getById(detail.getSetLocationId());
        outOrderParam.setSet_longitude(basicAddress2.getLongitude());
        outOrderParam.setSet_latitude(basicAddress2.getLatitude());

        BasicAddress basicAddress = basicAddressService.getById(detail.getGetLocationId());
        outOrderParam.setLongitude(basicAddress.getLongitude());
        outOrderParam.setLatitude(basicAddress.getLatitude());
        outOrderParam.setGetLocation(detail.getGetLocation());
        outOrderParam.setKilometer(detail.getKilometer());
        return ResponseData.success(outOrderParam);
    }

    /**
     * 选择收货地址
     * @param outCustomerId
     * @param model
     * @return
     */
    @RequestMapping("/toChoosePutGoods")
    public String toChoosePutGoods(@RequestParam("outCustomerId") Long outCustomerId, Model model){
        Long deliverId = userService.getDeliverId();
        model.addAttribute("deliverId",deliverId);
        model.addAttribute("outCustomerId",outCustomerId);
        return PREFIX + "/toPutGoods.html";
    }

    /**
     * 查询收货地址列表
     */
    @ResponseBody
    @RequestMapping("/ChoosePutGoods")
    public LayuiPageInfo ChoosePutGoods(BasicPutgoodsParam basicPutgoodsParam) {
    	User user = userService.getcurrentUser();
        basicPutgoodsParam.setDeliverId(user.getDeliverId());
        return this.basicPutgoodsService.findPageBySpec(basicPutgoodsParam,null,null,null);
    }

    /**
     * 查询列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(OutOrderParam outOrderParam,String condition ) {
    	User user = userService.getcurrentUser();
    	outOrderParam.setDeliverId(user.getDeliverId());
        outOrderParam.setDeptId(user.getDeptId());
        outOrderParam.setOutOrderStatus("list");
        return this.outOrderService.findPageBySpec(outOrderParam,condition,user.getOperateId());
    }

    /**
     * 查询收货单位列表
     */
    @ResponseBody
    @RequestMapping("/getUnitlist")
    public LayuiPageInfo getUnitlist(OutOrderParam outOrderParam,String condition ) {
    	//解决参数中的 英文括号
    	if (condition!=null&&condition!="") {
    		condition = condition.replace("& #40;", "(");
    		condition = condition.replace("& #41;", ")");
    	}
    	User user = userService.getcurrentUser();
        outOrderParam.setDeptId(user.getDeptId());
        outOrderParam.setDeliverId(user.getDeliverId());
        return this.outOrderService.getUnitlistPage(outOrderParam,condition,user.getOperateId());
    }

    /**
     * 查询出库订单列表
     */
    @ResponseBody
    @RequestMapping("/getQuerylist")
    public LayuiPageInfo getQuerylist(OutOrderParam outOrderParam,String condition ,String startTime,String endTime,String startTime2,String endTime2,String startTime3,String endTime3) {
    	User user = userService.getcurrentUser();
        outOrderParam.setDeptId(user.getDeptId());
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		outOrderParam.setCreateUserName("'"+startTime+"' and '"+endTime+"'");
		}
    	if (ToolUtil.isNotEmpty(startTime2) && ToolUtil.isNotEmpty(endTime2)) {
    		outOrderParam.setFinishOutUserName("'"+startTime2+"' and '"+endTime2+"'");
		}
    	if (ToolUtil.isNotEmpty(startTime3) && ToolUtil.isNotEmpty(endTime3)) {
    		outOrderParam.setSetMentiontime("'"+startTime3+"' and '"+endTime3+"'");
		} else if (startTime3 == null && endTime3 == null){
			startTime3 = DateUtil.getDate();
			endTime3 = DateUtil.getDate();
			outOrderParam.setSetMentiontime("'"+startTime3+"' and '"+endTime3+"'");
		}
        return this.outOrderService.QuerylistPageBySpec(outOrderParam,condition,user.getOperateId());
    }

    /**
     * 查询出库订单列表
     * 待确认
     */
    @ResponseBody
    @RequestMapping("/getConfirmlist")
    public LayuiPageInfo getConfirmlist(OutOrderParam outOrderParam,String condition ,String startTime,String endTime) {
    	User user = userService.getcurrentUser();
        outOrderParam.setDeptId(user.getDeptId());
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		outOrderParam.setCreateUserName("'"+startTime+"' and '"+endTime+"'");
		}
        return this.outOrderService.ConfirmlistPageBySpec(outOrderParam,condition,user.getOperateId());
    }


	/**
	 * 拉取
	 * @param model
	 * @return
	 */
	@RequestMapping("/toJSTOutOrder")
	public String toJSTOutOrder( Model model){
//		Long deliverId = userService.getDeliverId();
//		model.addAttribute("deliverId",deliverId);
//		model.addAttribute("outCustomerId",outCustomerId);
		User user = userService.getcurrentUser();
		Long deptId = user.getDeptId();
		Long deliverId = user.getDeliverId();
		//查询可选择仓库
		model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
		//查询可选择客户
		model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));

		return PREFIX + "/toJSTOutOrder.html";
	}


	/**
	 * 查询出库订单列表(聚水潭出库订单)
	 * 待出库
	 */
	@ResponseBody
	@RequestMapping("/getJSTOutOrder")
	public ResponseData getJSTOutOrder(ToolOrderPutParam toolOrderPutParam, String modified_begin, String modified_end){

		User user = userService.getcurrentUser();
		BasicCustomer byId = basicCustomerService.getById(132);
		String justAppsecret = byId.getJustAppsecret();
		String justAppkey = byId.getJustAppkey();
		String accessToken = byId.getAccessToken();

//		ApiResponse jstDdcx = JstDdcx.getJstDdcx(justAppkey, justAppsecret, accessToken,
//				null,modified_begin,modified_end);
//		System.out.println("jstDdcx:" + jstDdcx.toString());
//
//		ResponseData responseData = outOrderService.saveJstOutOrder(jstDdcx, user, byId);
		ResponseData responseData = new ResponseData();

		List<OrderPutExcelItem> list = new ArrayList<OrderPutExcelItem>();
		Integer page_index = 1;//页数
		boolean has_next = true;//是否有下一页
		while (has_next) {
			//只能分页查询，一页最多50条
			//接口调用频率秒级内不超过5次，分钟内不超过100次
			String data = null;
//			ApiResponse jstDdcx = null;
			try {
				data = justApi.getSellerItem(justAppkey,justAppsecret,accessToken, modified_begin, modified_end,null ,page_index.toString());
			} catch (IOException e) {
				e.printStackTrace();
			}
//			ObjectMapper mapper = new ObjectMapper();
//			try {
//				jstDdcx = mapper.readValue(data, ApiResponse.class);
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
			org.json.JSONObject jsonObject = new org.json.JSONObject(data);
			if(jsonObject.get("code").toString().equals("0")) {
				String data1 = jsonObject.get("data").toString();
				JSONObject jsonObject1 = new JSONObject(data1);
				if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
					if(jsonObject1.get("has_next").toString().equals("false")) {
						has_next = false;
					}
				responseData = outOrderService.saveJstOutOrder(jsonObject1, user, byId);

				} else {
					has_next = false;
					responseData.setSuccess(false);
					responseData.setMessage("未获取到快递明细");
				}
			} else {
				has_next = false;
				responseData.setSuccess(false);
				responseData.setMessage("拉取失败！"+data);
			}

			page_index++;
			if(has_next) {
				try {
					Thread.currentThread().sleep(650);//如果有下一页 等待0.65秒
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		return responseData;
	}

	/**
	 * 跳转到主页面
	 */
	@RequestMapping("jhzyjd")
	public String jhzyjd(Model model) {
		User user = userService.getcurrentUser();
		Long deptId = user.getDeptId();
		Long deliverId = user.getDeliverId();
		String currentDate = DateUtil.getDate();
//		model.addAttribute("jhzyjdList", basicCustomerService.findJhzyjdListByDeptId(deptId,currentDate));
		return PREFIX + "/jhzyjd.html";
	}


	@ResponseBody
	@RequestMapping("getJhzyjdList")
	public LayuiPageInfo getJhzyjdList(String currentDate ) {
		if(currentDate == null || currentDate.equals("")) {
			currentDate = DateUtil.getDate();
		}
		LayuiPageInfo pageInfo = new LayuiPageInfo();
		User user = userService.getcurrentUser();
		Long deptId = user.getDeptId();
		List<JHZYJDResult> jhzyjdListByDeptId = basicCustomerService.findJhzyjdListByDeptId(deptId, currentDate);

		pageInfo.setData(jhzyjdListByDeptId);
		return pageInfo;
	}
}


